import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login'
import Home from '@/views/Home'
import { Message } from 'element-ui'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta: {
      title: '登录界面'
    }
  },
  {
    path: '/home',
    name: 'home',
    component: Home,
    meta: {
      title: '主界面'
    },
    children: [
      {
        path: '/home',
        redirect: 'wellcome'
      },
      {
        path: 'wellcome',
        name: 'wellcome',
        component: () => import('@/views/Wellcome')
      },
      {
        path: 'businessList',
        name: 'basinessList',
        meta: {
          title: '商家列表'
        },
        component: () => import('@/views/business/BusinessList')
      },
      {
        path: 'businessAdd',
        name: 'basinessAdd',
        meta: {
          title: '新增商家'
        },
        component: () => import('@/views/business/BusinessAdd')
      },
      {
        path: 'businessUpdate',
        name: 'basinessUpdate',
        meta: {
          title: '新增商家'
        },
        component: () => import('@/views/business/BusinessUpdate')
      },
      {
        path: 'usersList',
        name: 'usersList',
        meta: {
          title: '用户列表'
        },
        component: () => import('@/views/users/UserList')
      },
      {
        path: 'ordersList',
        name: 'ordersList',
        meta: {
          title: '全部订单'
        },
        component: () => import('@/views/order/OrderList')
      },
      {
        path: 'dairyList',
        name: 'dairyList',
        meta: {
          title: '日志列表'
        },
        component: () => import('@/views/dairy/DairyList')
      },
      {
        path: 'dairyAdd',
        name: 'dairyAdd',
        meta: {
          title: '新增日志'
        },
        component: () => import('@/views/dairy/DairyAdd')

      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  if (to.name === 'login') {
    next()
  } else {
    let token = sessionStorage.getItem('token')
    if (token) {
      next()
    } else {
      Message.error('请先登录')
      next('/login')
    }
  }
})

export default router
